package com.dmz.task.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author lee
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Value("${cors.allowed}")
    private String urls;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        String[] split = urls.split(",");
        registry.addMapping("/**")
                // 允许的源，不要使用"*"
                .allowedOriginPatterns(split)
                // 允许的HTTP方法
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                // 允许的请求头
                .allowedHeaders("Origin", "Content-Type", "Accept", "Authorization")
                // 是否允许发送Cookie
                .allowCredentials(true)
                // 预检请求的缓存时间（秒）
                .maxAge(3600);
    }

    /*// 另一种方式：使用CorsFilter
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        
        // 设置允许的源
        config.setAllowedOriginPatterns(Arrays.asList("https://your-domain.com", "https://*.your-domain.com"));
        // 允许的HTTP方法
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        // 允许的请求头
        config.setAllowedHeaders(Arrays.asList("Origin", "Content-Type", "Accept", "Authorization"));
        // 是否允许发送Cookie
        config.setAllowCredentials(true);
        // 预检请求的缓存时间（秒）
        config.setMaxAge(3600L);
        
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }*/
}